package com.tank.action;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
import com.tank.bean.User;
import com.tank.core.TankModel;
import com.tank.service.MailService;
import com.tank.service.UserService;
import com.tank.vo.RetVo;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport {

	User user;
	TankModel tm;
	@Autowired
	@Qualifier("userService")
	UserService userService;

	@Resource(name = "mailService")
	MailService mailService;

	public TankModel getTm() {
		return tm;
	}

	public void setTm(TankModel tm) {
		this.tm = tm;
	}
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setLoginUserService(UserService userService) {
		this.userService = userService;
	}

	public String logout() throws Exception {

		if (userService.logout()) {
			return SUCCESS;
		}

		return ERROR;
	}

	public String login() throws Exception {
		
		if (user == null){
			tm=TankModel.newInstance();
			tm.setSuccess(false);
			tm.setMessage("请输入用户名和密码!");
			
			return INPUT;
		}
		
		tm = userService.checkUser(user);

		if (tm.isSuccess()) {
			return "home";
		}

		return INPUT;
	}

	public String register() throws Exception {
		if (user == null)
			return INPUT;
		
		if(user.getMail() != null && !user.getMail().matches("\\w+@\\w+\\.\\w+")){
			tm =TankModel.newInstance();
			tm.setSuccess(false);
			tm.setMessage("邮箱格式有错！（例：abc@qq.com）");
			
			user.setMail(null);
			
			return INPUT;
		}

		tm = userService.checkUserNameAndMail(user);
		tm.printSuccess();
		
		if(tm.isSuccess()){
			userService.registerUser(user);
			mailService.registerUser(user);
			tm.setMessage("注册成功!请注意查收验证邮件。。。");
			return "show";
		}else{
			return INPUT;
		}
		
		

	}


	public String r20() throws Exception {

		for (int i = 3; i < 23; i++) {
			user = new User("z" + i, "z" + i);
			user.setMail("z" + i + "@qq.com");
			userService.registerUser(user);
		}

		//sucess = "ok,20peo";

		return SUCCESS;

	}

}
